<template>
  <a-card :bordered="false">
    <a-form
      :form="form"
      layout="inline"
    >
      <a-card :bordered="false">
        <div
          slot="title"
          class="title"
        >
          <span>模型影响因子</span>

          <a-button
            v-if="isShowBestPredictBtn"
            type="primary"
            @click="loadBestPredict"
          >使用最优策略评估算法结果</a-button>
        </div>

        <div v-if="Object.keys(factorsByLayer).length !== 0">
          <a-form-item
            class="layer-box"
            v-for="(list, k) in factorsByLayer"
            :key="k"
            :label="k"
            :labelCol="{ span: 1 }"
            :wrapperCol="{ span: 23 }"
          >
            <div v-if="list.length > 0">
              <div
                class="factors-list"
                v-for="(d, i) in list"
                :key="d.id"
                :style="i > 2 ? { marginTop: '15px' } : {}"
              >
                <a-form-item>
                  <a-checkbox
                    :checked="enabledFactors.map(item => item.id).includes(d.id)"
                    :value="d.id"
                    @change="onEnabledFactorChange"
                  > {{ d.factorName }} </a-checkbox>
                </a-form-item>

                <a-form-item label="样本">
                  <a-input
                    autocomplete="off"
                    style="width: 125px"
                    :max-length="6"
                    :addon-after="d.unit"
                    @keyup="clearNoNum('scoreSample_' + d.id)"
                    @blur="clearNoNum('scoreSample_' + d.id)"
                    v-decorator="[
                    'scoreSample_' + d.id,
                    {
                      initialValue: d.scoreSample,
                      rules: [
                        { required: true, message: '请输入' + d.factorName + '样本' },
                        { validator: validators.xmax({ max: (d.unit === '%' ? 100 : 999999) }), trigger: 'change', },
                        { validator: validators.xmin({ min:0 }), trigger: 'change', },
                      ],
                    },
                  ]"
                  />
                </a-form-item>
              </div>
            </div>
            <span
              v-else
              style="margin-left: 10px;"
            >暂无模型影响因子</span>
          </a-form-item>
        </div>
        <span v-else>暂无模型影响因子</span>
      </a-card>

      <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
        <a-button
          type="primary"
          @click="handleSubmit"
        > 提交 </a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
  import { gPostAction } from "@/api/manage"
  import { filterNoNum } from "@/utils/util";

  export default {
    name: 'EditModelFactors',
    props: {
      // OPTIMAL_COST 最优成本
      // OPTIMAL_DEVICE 最优设备
      // AIR 制冷设备
      // UPS 供电设备
      module: {
        type: String,
        default: ''
      },
      content: {
        type: String,
        default: ''
      },
      modelType: {
        type: String,
        default: ''
      },
      isShowBestPredictBtn: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        form: this.$form.createForm(this, { name: 'coordinated' }),
        factorsByLayer: {
          'L0': [],
          'L1': [],
          'L2': [],
          'L3': [],
          'L4': []
        },
        factors: [],
        enabledFactors: [],
        factorsMap: {},
      }
    },
    mounted() {
      if (this.modelType) {
        this.getModelFactors(this.modelType)
      }
    },
    watch: {
      modelType(val) {
        if (val) {
          this.getModelFactors(val)
        }
      }
    },
    methods: {
      clearNoNum(fieldName) {
        let obj = {};
        obj[fieldName] = filterNoNum(this.form.getFieldValue(fieldName));
        this.form.setFieldsValue(obj);
        this.form.validateFields([fieldName], (errors, values) => {});
      },
      getModelFactors(modelType) {
        const postData = { modelType };
        postData.title = this.module;

        gPostAction('/model/getModelFactors', postData).then((res) => {
          if (res.success) {
            this.factors = res.data || []
            this.factors.forEach((d) => {
              this.factorsByLayer[d.layer].push(d)
              this.factorsMap[d.id] = d
            })
            this.enabledFactors = res.data.filter(item => item.enabled === true)
          }
        })
      },
      loadBestPredict() {
        let postData = {};
        if (this.modelType == 'OPTIMAL_DEVICE') {
          postData = { modelType: this.modelType, title: "精确管控与供电制冷联动-统一管理联动平台-最优设备模型-最优设备模型设置", content: "使用最优策略评估算法结果" }
        } else if (this.modelType == 'OPTIMAL_COST') {
          postData = { modelType: this.modelType, title: "精确管控与供电制冷联动-统一管理联动平台-最优成本模型-最优成本模型设置", content: "使用最优策略评估算法结果" }
        } else {
          postData = { modelType: this.modelType }
        }
        gPostAction('/model/bestPredict', postData).then((res) => {
          if (res.success) {
            const predict = {}
            for (let i = 0; i < res.vos.length; i++) {
              const predictItem = this.factors.filter(_ => _.factorName === res.vos[i].factorName)
              if (predictItem.length === 0) { break }
              predict['scoreSample_' + predictItem[0].id] = res.vos[i].scoreBestPredict
            }
            this.$message.success('获取成功')
            this.form.setFieldsValue(predict)
          }
        })
      },
      handleSubmit(e) {
        this.form.validateFields((err, values) => {
          if (!err) {
            const requestData = {
              modelType: this.modelType,
              title: this.module,
              content: this.content,
              factors: []
            }
            let length = 0
            this.enabledFactors.forEach((item, index) => {
              requestData['factors[' + index + '].id'] = item.id
              requestData['factors[' + index + '].scoreSample'] = values['scoreSample_' + item.id]
              // requestData['factors[' + index + '].scoreType'] = values['scoreType_' + item.id]
              requestData['factors[' + index + '].factorName'] = this.factorsMap[item.id] ? this.factorsMap[item.id].factorName : ''
              // requestData['factors[' + index + '].weight'] = values['weight_' + item.id]
              requestData['factors[' + index + '].enabled'] = true
              length += 1
            })

            // 没有选中的
            this.factors.filter(_ => !this.enabledFactors.map(d => d.id).includes(_.id)).forEach((item, i) => {
              const index = length + i
              requestData['factors[' + index + '].id'] = item.id
              requestData['factors[' + index + '].scoreSample'] = 0
              // requestData['factors[' + index + '].scoreType'] = item.scoreType
              requestData['factors[' + index + '].factorName'] = item.factorName
              // requestData['factors[' + index + '].weight'] = 0
              requestData['factors[' + index + '].enabled'] = false
            })

            gPostAction('/model/setModelFactors', requestData).then(res => {
              if (res.success) {
                this.$message.success('提交成功')
              }
            })
          }
        })
      },
      onEnabledFactorChange(e) {
        const id = e.target.value
        if (e.target.checked) {
          const factor = Object.assign({}, this.factors.filter(item => item.id === id)[0])
          this.enabledFactors.push(factor)
        } else {
          this.enabledFactors = this.enabledFactors.filter(item => item.id !== id)
        }
      }
    },
  }
</script>

<style
  lang="less"
  scoped
>
  .title {
    display: flex;
    justify-content: space-between;
  }

  .layer-box {
    display: block;
    width: 100%;

    &:not(:first-child) {
      margin-top: 40px;
    }

    .factors-list {
      padding-left: 10px;
      display: inline-block;
      width: 33%;

      /deep/ .ant-row.ant-form-item {
        margin-right: 0;
        width: 44%;

        &:last-of-type {
          width: 55%;
        }
      }
    }
  }
</style>